package com.johnson.news.fragment;


import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.johnson.news.R;
import com.johnson.news.activity.ContactusActivity;
import com.johnson.news.activity.LoginActivity;
import com.johnson.news.activity.ModifyPwdActivity;
import com.johnson.news.activity.MyCollectActivity;
import com.johnson.news.activity.OfficalWeiXinActivity;
import com.johnson.news.activity.OfficialWeiboActivity;
import com.johnson.news.activity.RegisterActivity;
import com.johnson.news.activity.WebViewActivity;
import com.johnson.news.databinding.FragmentSettingBinding;
import com.johnson.news.event_msg.LoginMsg;
import com.johnson.news.model.util.NewsPreference;
import com.johnson.news.util.Constants;
import com.johnson.news.util.Utils;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.youmbe.library.BaseBindingFragment;
import com.youmbe.library.util.MyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;

import static com.johnson.news.activity.WebViewActivity.intent_key_url;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link SettingFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SettingFragment extends BaseBindingFragment<FragmentSettingBinding> {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;


    public SettingFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SettingFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SettingFragment newInstance(String param1, String param2) {
        SettingFragment fragment = new SettingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

        EventBus.getDefault().register(this);
    }

    View rootView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if(rootView == null)
            rootView = super.onCreateView(inflater, container, savedInstanceState);
        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    String glideCachePath;
    @Override
    public void init() {
        dataBinding.setOnClickListener(onClickListener);

        glideCachePath = getActivity().getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;

        NewsPreference newsPreference = new NewsPreference(getActivity());
        if (newsPreference.getLoginState())
            onLogin(newsPreference.getLoginName());
        else
            onLogout();

        initCacheSize();
    }

    void initCacheSize() {
        long fileSize = Utils.getFileSize(new File(glideCachePath));

        if(fileSize > 0)
            dataBinding.settingClearCache.setText(getString(R.string.setting_clear_cache) + "(" + Utils.formetFileSize(fileSize) + ")");
        else
            dataBinding.settingClearCache.setText(getString(R.string.setting_clear_cache));
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.setting_register:
                    startActivity(RegisterActivity.class, null);
                    break;
                case R.id.setting_login:
                    startActivity(LoginActivity.class, null);
                    break;
                case R.id.setting_modify_pwd:
                    startActivity(ModifyPwdActivity.class, null);
                    break;
                case R.id.setting_clear_cache:
                    clearCache();
                    break;
                case R.id.setting_collect:
//                    if(NewsPreference.getinstance(getActivity()).getLoginState())
                        startActivity(MyCollectActivity.class, null);
//                    else {
//                        startActivity(LoginActivity.class, null);
//                        MyToast.showToast("您还没有登录", getActivity());
//                    }

                    break;
                case R.id.setting_connect_us:
                    startActivity(ContactusActivity.class, null);
                    break;
                case R.id.setting_website:
                    Bundle bundle = new Bundle();
                    bundle.putString(intent_key_url, Constants.officialWebsite);
                    startActivity(WebViewActivity.class, bundle);
                    break;
                case R.id.setting_weibo:
                    startActivity(OfficialWeiboActivity.class, null);
                    break;
                case R.id.setting_weixin:
                    startActivity(OfficalWeiXinActivity.class, null);
                    break;
                case R.id.setting_update:
                    Utils.checkUpdate(getActivity(), false);
                    break;
                case R.id.setting_logout:
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setMessage(getString(R.string.setting_logout_ensure));
                    builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            NewsPreference pref = NewsPreference.getinstance(getActivity());//保存信息这一段代码，在原工程里只在注册时有。
                            pref.setToken("");
                            pref.setLoginName("");
                            pref.setLoginState(false);
                            onLogout();
                        }
                    });
                    builder.show();
                    break;
            }
        }
    };

    void clearCache(){
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                Utils.deleteDir(new File(glideCachePath));
                emitter.onNext(glideCachePath);
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>() {
                    @Override
                    public void accept(String s) throws Exception {
                        initCacheSize();
                    }
                });
    }

    void onLogin(String phone) {
        dataBinding.settingLoginUser.setVisibility(View.VISIBLE);
        dataBinding.settingLoginUser.setText(phone);
        dataBinding.settingRegister.setVisibility(View.GONE);
        dataBinding.settingModifyPwd.setVisibility(View.VISIBLE);
        dataBinding.settingLogin.setText(R.string.setting_logined);
        dataBinding.settingLogout.setVisibility(View.VISIBLE);
    }

    void onLogout() {
        dataBinding.settingLoginUser.setVisibility(View.GONE);
        dataBinding.settingLoginUser.setText("");
        dataBinding.settingRegister.setVisibility(View.VISIBLE);
        dataBinding.settingModifyPwd.setVisibility(View.GONE);
        dataBinding.settingLogin.setText(R.string.setting_login);
        dataBinding.settingLogout.setVisibility(View.GONE);
    }

    @Subscribe
    public void onLoginSuccess(LoginMsg loginMsg) {
        onLogin(loginMsg.phone);
    }

    @Override
    public int getContentViewId() {
        return R.layout.fragment_setting;
    }

}
